package demos;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class Barrier implements Runnable {
	CyclicBarrier barrier;
	private static int count = 0;

	public Barrier(CyclicBarrier barrier) {
		this.barrier = barrier;
	}

	@Override
	public void run() {
		try {
			Thread.sleep((long) (Math.random() * 100));
			System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点1，当前已有" + barrier.getNumberWaiting()
					+ "个已经到达，正在等候");
			barrier.await();// 到此如果没有达到公共屏障点，则该线程处于等待状态，如果达到公共屏障点则所有处于等待的线程都继续往下运行

			Thread.sleep((long) (Math.random() * 100));
			System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点2，当前已有" + barrier.getNumberWaiting()
					+ "个已经到达，正在等候");
			barrier.await();
			Thread.sleep((long) (Math.random() * 100));
			System.out.println("线程" + Thread.currentThread().getName() + "即将到达集合地点3，当前已有" + barrier.getNumberWaiting()
					+ "个已经到达，正在等候");
			barrier.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public class CyclicBarrierTest {
	public static void main(String[] args) {
		CyclicBarrier barrier = new CyclicBarrier(3);
		ExecutorService exec = Executors.newCachedThreadPool();
		for (int i = 0; i < 3; i++)
			exec.execute(new Barrier(barrier));
		exec.shutdown();
	}
}
